package com;


import java.util.ArrayList;

/**
 * Created by MingNuo on 2017/3/10.
 */

public class FormatUtils {
    /**
     * 将byte[] 转成 16进制 String
     *
     * @param bytes
     * @return
     */
    public static String bcd2Str(byte[] bytes) {
        StringBuffer temp = new StringBuffer(bytes.length * 2);
        char[] temp1 = {'A', 'B', 'C', 'D', 'E', 'F'};

        for (int i = 0; i < bytes.length; i++) {
            if (((bytes[i] & 0xf0) >> 4) <= 9) {
                temp.append((byte) ((bytes[i] & 0xf0) >> 4));
            } else {
                temp.append(temp1[((bytes[i] & 0xf0) >> 4) - 10]);
            }
            if ((bytes[i] & 0x0f) <= 9) {
                temp.append((byte) (bytes[i] & 0x0f));
            } else {
                temp.append(temp1[(bytes[i] & 0x0f) - 10]);
            }
        }
        return temp.toString();
    }


    /**
     * char to bytes
     *
     * @param c
     * @return
     */
    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }

    /**
     * byte to char
     *
     * @param b
     * @return
     */
    public static char byteToChar(byte[] b) {
        char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF));
        return c;
    }


    /**
     * @param num:要获取二进制值的数
     * @param index:倒数第一位为0，依次类推
     */
    public static int getBinaryValue(int num, int index) {
        return (num & (0x1 << index)) >> index;
    }

    public static int getBinaryValue(byte num, int index) {
        return (num & (0x1 << index)) >> index;
    }


    //将字符串 变成N位 前置补0
    public static String getStrByDigit(String value, int digit) {
        if (value.length() >= digit) {
            return value;
        }
        int num = digit - value.length();
        for (int i = 0; i < num; i++) {
            value = "0" + value;
        }
        return value;
    }


    public static void reverseArray(String[] Array) {
        ArrayList<String> array_list = new ArrayList<String>();
        for (int i = 0; i < Array.length; i++) {
            array_list.add(Array[Array.length - i - 1]);
        }
        Array = array_list.toArray(Array);

    }


    public static char[] reverseArray(char[] Array) {
        char[] newChar = new char[Array.length];
        for (int i = 0; i < Array.length; i++) {
            newChar[i] = Array[Array.length - i - 1];
        }
        return newChar;

    }


}
